const path = require('path')
const webpack = require('webpack')
const HtmlWebpackInlinePlugin = require('html-webpack-inline-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css']
const moment = require('moment')
process.env.VUE_APP_TIME = moment().format('YYYY.MM.DD HH:mm:ss')

function resolve(dir) {
    return path.join(__dirname, dir)
}

const isProd = process.env.NODE_ENV === 'production'

// vue.config.js
const vueConfig = {
    publicPath: './',
    // outputDir: 'dist-' + process.env.ENV,
    outputDir: 'dist',
    runtimeCompiler: true,
    configureWebpack: config => {
        if (isProd) {
            //关闭 webpack 的性能提示
            config.performance = {
                hints: false,
            }
            config.plugins.push(
                new UglifyJsPlugin({
                    uglifyOptions: {
                        warnings: false,
                        compress: {
                            drop_debugger: true,
                            drop_console: true,
                            pure_funcs: ['console.log'],
                        },
                    },
                    sourceMap: false,
                    parallel: true,
                }),
                new CompressionWebpackPlugin({
                    algorithm: 'gzip',
                    test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
                    threshold: 10240,
                    minRatio: 0.8,
                }),
            )
        }
        return {
            plugins: [
                new HtmlWebpackInlinePlugin({
                    compress: false,
                }),
                // Ignore all locale files of moment.js
                new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
            ],
        }
    },
    chainWebpack: config => {
        // set svg-sprite-loader
        config.module.rule('svg').exclude.add(resolve('src/icons')).end()
        config.module
            .rule('icons')
            .test(/\.svg$/)
            .include.add(resolve('src/icons'))
            .end()
            .use('svg-sprite-loader')
            .loader('svg-sprite-loader')
            .options({
                symbolId: 'icon-[name]',
            })
            .end()
        config.module
            .rule('vue')
            .use('vue-loader')
            .loader('vue-loader')
            .tap(options => {
                options.compilerOptions.directives = {
                    html(node, directiveMeta) {
                        // onIgnoreTagAttr 自定义匹配到不在白名单上的属性时的处理方法
                        ;(node.props || (node.props = [])).push({
                            name: 'innerHTML',
                            value: `xss(_s(${directiveMeta.value}), {
                      onIgnoreTagAttr: function (tag, name, value, isWhiteAttr) {
                        return name + '="' + value + '"';
                      },
                    })`,
                        })
                    },
                }
                return options
            })
        config.plugin('html').tap(args => {
            if (isProd) {
                args[0].minify.removeComments = false
            }
            args[0].title = process.env.VUE_APP_CITY_TITLE
            args[0].favicon = resolve('public/favicon-' + process.env.VUE_APP_CITY + '.ico')
            return args
        })
        config.resolve.alias.set('@$', resolve('src'))
    },

    css: {
        sourceMap: true,
        loaderOptions: {
            sass: {
                additionalData: '@import "@/assets/styles/mixin.scss";',
            },
            less: {
                lessOptions: {
                    javascriptEnabled: true,
                },
            },
        },
    },
    lintOnSave: true, // error警告也会导致编译失败;default错误才会导致编译失败;true/warning仅输出到命令行，不会使编译失败。

    devServer: {
        // development server port 8000
        port: 7000,
        open: false,
        // 让浏览器 overlay 同时显示eslint的警告和错误
        overlay: {
            warnings: false,
            errors: false,
        },
        proxy: {
            '/aqcs': {
                // target: process.env.VUE_APP_API,
                target: 'https://apiaqsfcs.scdem.cn',
                changeOrigin: true,
            },
            '/file': {
                target: 'https://api-file.scdem.cn',
                changeOrigin: true,
                pathRewrite: {
                    '^/file': '/',
                },
            },
        },
    },

    // disable source monitor-map in production
    productionSourceMap: false,

    // babel-loader no-ignore node_modules/*
    transpileDependencies: ['vue-echarts', 'resize-detector'],
}

module.exports = vueConfig
